<?php
namespace Futures\Controller;
use Think\Controller;
use Futures\Model\OptionModel;
/**
 *  恒指期权控制器
 */
class BiteOptionController extends BaseController{
  
    public function index(){
        //cookie('user_auth',$user);
        $user_auth= cookie('user_auth');
        $openid=$user_auth['openid'];
        //获取账户余额
        $user_money = M('Follow')->where(array('openid'=>$user_auth['openid']))->getField('money');
        //dump($user_money);
        $this->assign('money',$user_money);
        $option = M('FuturesOption')->where(array('type'=>6))->find();
        $datas = get_bite_data();  //1是卖价、3是买价、5是开盘价、9是最新价
        
        $this->assign('option',$option);
        $this->assign('datas',$datas);
        $this->display();
    }

	

    public function load_ongoing(){
        header("Access-Control-Allow-Origin:*");
        header('Content-Type:application/json; charset=utf-8');
        //$user=array('uid'=>412,'openid'=>'o6VUpxI3SRM2vaw9FJIMUmxjO2to');
        //cookie('user_auth',$user);
        $user_auth= cookie('user_auth');
        $openid=$user_auth['openid'];

        //$option = M('FuturesOption')->where(array('status'=>1,'type'=>5))->find();
        $option_datas = get_bite_data();  //1是卖价、2是买价、9是最新价

        $M= new OptionModel('biteorder');
        $map['user_id'] = $user_auth['uid'];
        $map['sell_price'] = array('lte',0);
        $map['end_time'] = array('gt',time());
        $map['status'] = 1;
        $list = $M->where($map)->order('id desc')->select();
        
        //dump($option_datas);
        //$option_datas = array();
        $new = array();
        foreach ($list as $k => $v) {
            $v['last_price'] = $option_datas['last_price'];
            if($v['direction']){    //看涨
                $p= $option_datas['last_price']-$v['buy_price'];
            }else{
                $p = $option_datas['last_price']-$v['buy_price'];
            }
            if($p<0){
                $v['profit'] = -$v['invest'];
            }elseif($p==0){
                $v['profit'] = 0;
            }else{
                $v['profit'] = $v['invest']*(1+$v['yield_rate']);
            }
            $v['format_start_time'] = date('Y-m-d H:i:s',$v['start_time']);
            $v['cur_time'] = time();
            $v['shen'] = $v['end_time']-time();
            $v['direction_str']=$v['direction']?"看涨":"看跌";
            $new[] = $v;
        }
        exit(json_encode($new));
    }

    public function load_over(){
       // $user=array('uid'=>412,'openid'=>'o6VUpxI3SRM2vaw9FJIMUmxjO2to');
        //cookie('user_auth',$user);
        $user_auth= cookie('user_auth');
        $openid=$user_auth['openid'];
        $M= new OptionModel('biteorder');
        $map['user_id'] = $user_auth['uid'];
        $map['status'] = 2;
        $page = I('post.page')?:1;
        $listRow = 5;
        $firstRow = ($page-1)*$listRow;
        $list = $M->where($map)->order('end_time desc')->limit($firstRow.",".$listRow)->select();
        $new = array();
        foreach ($list as $k => $v) {
            $v['format_start_time'] = date('Y-m-d H:i:s',$v['start_time']);
            $v['format_end_time'] = date('Y-m-d H:i:s',$v['end_time']);
            $v['direction_str']=$v['direction']?"看涨":"看跌";
            $new[] = $v;
        }
        exit(json_encode($new));
    }

    public function order_insert(){
        //$user=array('uid'=>412,'openid'=>'o6VUpxI3SRM2vaw9FJIMUmxjO2to');
        //cookie('user_auth',$user);
        $user_auth= cookie('user_auth');
        $openid=$user_auth['openid'];
        $user_id=$user_auth['uid'];

        $M= new OptionModel('biteorder');//movie是集合名（表名）

        //计算正在进行中的合约订单总和不能超过两万
        // $going['user_id'] = $user_id;
        // $going['staus'] = 1;
        // $total_invest = $M->where(going)->sum('invest');
        // if($total_invest>20000){
        //     $this->error('进行中订单总额已过20000，请稍后再下单');
        // }
        $option = M('FuturesOption')->where(array('status'=>1,'type'=>6))->field('name,code,status')->find();
        $option_datas = get_bite_data();  //1是卖价、2是买价、9是最新价
        $time=time();                       //开始时间
        $option_id = I('option_id');        //合约id
        
        if(!$option || empty($option['status'])){
            $this->error('期权已停止下单');
        }
        $duration = I('post.duration');     //时长

        if(date('Ymd',$option_datas['time']) != date('Ymd')){
            $this->error('休市期间');
        }

        //交易时间判断 交易日周六周日 节假读文件
        //先读取文件判断是否是节假日
		$is_monday = date("w");
		$one_point = mktime(6,00,00,date('m'),date('d'),date('Y'));
		if(!($is_monday==6 || $is_monday==0 || ($is_monday==1 && (time()+$duration)<$one_point ))){
			$this->error('休市期间');
		}
        $holidayfile = './Data/holidays.txt';
        if(file_exists($holidayfile)){
            $holidays=file_get_contents($holidayfile);
            if(!empty($holidays)){
                //逗号分隔
                $holidays = explode(',',$holidays);
                $currnt_date = date('Y-m-d');
                if(in_array($currnt_date, $holidays)){
                     //$this->error('休市期间');
                }
            }
        }
        //然后判断时候是当日交易时间段
        $one_start = mktime(9,15,00,date('m'),date('d'),date('Y'));
        $one_end = mktime(12,00,00,date('m'),date('d'),date('Y'));
        
        $two_start = mktime(13,00,00,date('m'),date('d'),date('Y'));
        $two_end = mktime(16,15,00,date('m'),date('d'),date('Y'));

        $three_start = mktime(17,00,00,date('m'),date('d'),date('Y'));
        $three_end = mktime(23,45,00,date('m'),date('d'),date('Y'));
        
        // if(!(((time()+$duration)>$one_start&&(time()+$duration)<$one_end)||((time()+$duration)>$two_start&&(time()+$duration)<$two_end) || ((time()+$duration)>$three_start&&(time()+$duration)<$three_end))){
        //     $this->error('不在交易时段');exit;
        // }
        if(!(((time())>$one_start&&(time()+$duration)<$one_end)||((time())>$two_start&&(time()+$duration)<$two_end) || ((time())>$three_start&&(time()+$duration)<$three_end))){
            //$this->error('不在交易时段');exit;
        }

        $direction = I('post.direction');   //方向
        $yield_rate = I('post.yield_rate'); //收益率
        $end_time = $time+$duration;       //结束时间
        $invest = I('post.invest');         //投资金额
        $invest = floatval($invest);
        //判断投资金额
        if($invest <= 0){
            $this->error('请选择正确的投资金额!');
        }
        
        if($option_datas['last_price']<1 || $option_datas['buy_price']<1 || $option_datas['sell_price']<1){
            $this->error('系统维护中!');
        }

        //获取用户的金额
        $user_money = M('Follow')->where(array('openid'=>$user_auth['openid']))->getField('money');
        if($user_money<$invest){
            $this->error('余额不足，请充值!');
        }
        if($direction==1){
            $open_price = $option_datas['sell_price'];
        }elseif($direction==0){
            $open_price = $option_datas['buy_price'];
        }
        
        $transaction_id=date('YmdHis').$rand;
        $option_name = $option['name']."(".$option['code'].")";
        $data=array(
            'transaction_id'=>$transaction_id,   //订单编号
            'user_id'=>$user_id,                     //购买用户
            'option_id'=>$option_id,            //期权合约id
            'option_name'=>$option_name,        //合约名称
            'invest'=>$invest,                  //投资金额
            'buy_price'=>$open_price, //当前卖价
            'sell_price'=>0.00,                 //平仓买价
            'direction'=>$direction,            //0-看跌 1-看涨
            'profit'=>0.00,                     //盈利
            'start_time'=>$time,                //开始时间
            'duration'=>$duration,              //时长 s
            'yield_rate'=>$yield_rate,          //收益率
            'end_time'=>$end_time,              //结束时间
            'status'=>1,                        //1进行中 2已结束
            'has_maker_log'=>0,
        );
        $res = $M->add($data);
        //$this->success('执行成功！');
        if($res){
            modify_account($openid,-$invest,3,'比特币期权建仓支付');
            //下单支付（type=3）有分销提成
            $route = M('Follow')->where(array('openid'=>$user_auth['openid']))->getField('route');
            if(!empty($route)){
                $routes = explode(',',$route);
                krsort($routes);
                $routes = array_values($routes);
                $commission = M('Config')->where(array('name'=>'COMMISSION_VAL'))->getField('value');
                $commissions = explode(',',$commission);
                foreach($commissions as $k=>$v){
                    $is_agent = M('Follow')->where(array('id'=>$routes[$k]))->getField('is_agent');
                    if(!$is_agent) continue;
                    $comm = array();
                    $comm['order_user_id'] = $user_auth['uid']; //下单者
                    $comm['commission_user_id'] = $routes[$k]; //提成者
                    $comm['order_id'] = $res;  //订单id
                    $comm['type'] = 1;
                    $comm['status'] = 0;    //未分配
                    $comm['create_time'] = time();
                    if(strpos($v,'%')>0){
                         $v = $v/100;
                    }
                   
                    $comm['commission'] = abs($invest)*$v;   //佣金
                    $comm['note'] = "比特币订单：{$data['transaction_id']}佣金提成".(abs($invest)*$v).'元';
                    //写入佣金表
                    $res = M('FuturesCommission')->add($comm);
                    if(false === $res){
                        //写入日志
                        $nickname = M('Follow')->where(array('id'=>$routes[$k]))->getField('nickname');
                        $file='./Data/optioncommission.txt';
                        $content = date('Ymd His').':'.$nickname.'写入(比特币期权)佣金【订单('.$data['transaction_id'].')】失败;\r\n';
                        file_put_contents($file,$content, FILE_APPEND);
                    }
                }
            }
            $this->success('执行成功！');
        }else{
            $this->error('执行失败！');
        }          
    }

    public function rules(){
        $this->display();
    }
}
